package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import com.itheima.reggie.util.WeatherDown;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrdersService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private TimeWayService timeWayService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @CacheEvict(value = "orderCache", allEntries = true)
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);

        orderService.submit(orders);
        return R.success("下单成功！");
    }

    /**
     * 后台查看所有订单
     * @param page
     * @param pageSize
     * @param name
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name,String number,String beginTime,String endTime){
        log.info("page:{},pageSize:{},name:{},number:{},beginTime:{},endTime:{}",page,pageSize,name,number,beginTime,endTime);
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,Orders::getUserName,name);
        queryWrapper.like(number!=null,Orders::getId,number);
        queryWrapper.between(beginTime!=null && endTime!=null,Orders::getOrderTime,beginTime,endTime);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(ordersPage,queryWrapper);
        return R.success(ordersPage);
    }


    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(Integer page, Integer pageSize) {
        // 设置分页参数
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        // 设置查询条件
        lqw.eq(Orders::getUserId, BaseContext.getCurrentId());
        // 排序条件
        lqw.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo, lqw);

        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");

        List<OrdersDto> ordersDtos = pageInfo.getRecords().stream().map(item -> {
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, item.getId());
            // 查找订单详情
            List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper);

            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtos);
        return R.success(ordersDtoPage);
    }

    @PutMapping
    public R<Orders> status(@RequestBody Orders orders){
        orderService.updateById(orders);

        return R.success(orders);
    }

    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        //根据订单id，获取到订单详情
        Long ordersId = orders.getId();
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,ordersId);
        List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLambdaQueryWrapper);
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = orderDetails.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item, shoppingCart);
            shoppingCart.setUserId(userId);

            return shoppingCart;
        }).collect(Collectors.toList());

        for (ShoppingCart shoppingCart : shoppingCarts) {
            shoppingCartService.save(shoppingCart);
        }
        return R.success("再来一单成功！");
    }
    @GetMapping("/money")
    public R<Integer> money() throws Exception {
        LocalDateTime now = LocalDateTime.now();
        String s = now.toString();
        String substring = s.substring(0, 4);
        String substring1 = s.substring(5, 7);
        String today = s.substring(0, 10);
        String path = substring + substring1;
        ArrayList<Weather> weathers = WeatherDown.weather(path);
        String todayWeather = "";

        for (Weather weather : weathers) {
            if (weather.getDate().equals(today)) {
                todayWeather = weather.getWeather();
            }
        }
        log.info("天气：{}", todayWeather);
        Long id = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null,AddressBook::getUserId,id) ;
        lqw.eq(id != null,AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(lqw);
        Double wakKm = 1.5;
        if (addressBook != null){
            Long addressBookId = addressBook.getId();
            LambdaQueryWrapper<TimeWay> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TimeWay::getAddressId,addressBookId);
            List<TimeWay> list = timeWayService.list(queryWrapper);
            TimeWay timeWay = list.get(0);
            String way = timeWay.getWay();
            String[] split = way.split("公");
            wakKm = Double.parseDouble(split[0]);
        }
        int money = 6;
        if (wakKm > 2.0 && wakKm<= 5.0){
            money = money+5;
        }
        if (wakKm > 5.0 && wakKm<= 10.0){
            money = money+20;
        }
        if (wakKm > 10.0){
            money = money+30;
        }

        String[] ws = {
                "晴天",
                "阴",
                "多云",
                "晴转多云",
                "多云转晴",
                "晴转阴",
                "阴转晴",
                "多云转阴",
                "阴转多云"
        };
        for (String w : ws) {
            if (w.equals(todayWeather)) {
                return R.success(money);
            }
        }
        if (todayWeather.contains("雨")){
            return R.success(money+5);
        }
        if (todayWeather.contains("雪")){
            return R.success(money+10);
        }
        return R.success(money+20);
    }


    //获取外卖配送距离和到达时间
    @PostMapping("/timeWay")
    public void countTW(String timeBaidu,String wayBaidu){
        TimeWay timeWay = new TimeWay();
        timeWay.setTime(timeBaidu);
        timeWay.setWay(wayBaidu);
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,userId).
                eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);
        //判断是否配送过这个地址的订单
        LambdaQueryWrapper<TimeWay> timeWayLambdaQueryWrapper = new LambdaQueryWrapper<>();
        timeWayLambdaQueryWrapper.eq(TimeWay::getAddressId,addressBook.getId());
        List<TimeWay> timeWayList = timeWayService.list(timeWayLambdaQueryWrapper);
        if (timeWayList.size()==0){
            timeWay.setAddressId(addressBook.getId());
            timeWayService.save(timeWay);
        }
    }
    @GetMapping("/show")
    public R<TimeWay> show(){
        Long id = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null,AddressBook::getUserId,id) ;
        lqw.eq(id != null,AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(lqw);
        if (addressBook == null){
            TimeWay timeWay = new TimeWay();
            timeWay.setTime("12分钟");
            timeWay.setWay("1.5公里");
            return R.success(timeWay);
        }
        Long addressBookId = addressBook.getId();
        LambdaQueryWrapper<TimeWay> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(addressBookId != null,TimeWay::getAddressId,addressBookId);
        List<TimeWay> list = timeWayService.list(queryWrapper);
        TimeWay timeWay = list.get(0);
        return R.success(timeWay);
    }
    @GetMapping("/weather")
    public R<String> weatherShow() throws Exception {
        LocalDateTime now = LocalDateTime.now();
        String s = now.toString();
        String substring = s.substring(0, 4);
        String substring1 = s.substring(5, 7);
        String today = s.substring(0, 10);
        String path = substring + substring1;
        ArrayList<Weather> weathers = WeatherDown.weather(path);
        String todayWeather = "";

        for (Weather weather : weathers) {
            if (weather.getDate().equals(today)) {
                todayWeather = weather.getWeather();
            }
        }

        return R.success(todayWeather);
    }

}
